//
//  YCNetworManager.m
//  YCSchool
//
//  Created by gmall on 16/5/6.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  网络工具类

#import "YCNetworManager.h"

#pragma mark - UploadFile

@interface UploadFile()

@end

@implementation UploadFile

- (instancetype)initWithType:(UploadFileType)type data:(NSData *)data key:(NSString *)key
{
    if(self = [super init])
    {
        _data = [data copy];
        _type = type;
        _key = [key copy];
        self.fileName = [NSString yc_guidString];//生成唯一字符串
        NSString *ps = @"";
        
        switch (type)
        {
            case UploadFileTypeImage:
                self.fileName = [self.fileName stringByAppendingPathExtension:@"jpg"];
                self.mimeType = @"image/jpeg";
                CGSize size = [UIImage imageWithData:data].size;
                ps = [NSString stringWithFormat:@"?pw=%ld&ph=%ld",(long)size.width,(long)size.height];//这个根据情况来定
                break;
                
            case UploadFileTypeAudio:
                self.fileName = [self.fileName stringByAppendingPathExtension:@"amr"];
                self.mimeType = @"audio/amr";
                break;
                
            case UploadFileTypeVideo:
                self.fileName = [self.fileName stringByAppendingPathExtension:@"mp4"];
                self.mimeType = @"video/mp4";
                break;
                
            default:
                break;
        }
        self.fileName = [NSString stringWithFormat:@"ios_%@",self.fileName];//文件名
        
        NSString *tmp = NSTemporaryDirectory();
        self.localPath = [tmp stringByAppendingPathComponent:self.fileName];//用来存本地时的路径
        _remotePath = [NSString stringWithFormat:@"http://imgs.gonecn.com/%@%@",self.fileName,ps];//url地址
    }
    return self;
}

- (BOOL)saveToTemp
{
    if(self.data)
    {
        return [self.data writeToFile:self.localPath atomically:YES];
    }
    return NO;
}

+ (instancetype)uploadFileWihType:(UploadFileType)type data:(NSData *)data key:(NSString *)key
{
    return [[self alloc] initWithType:type data:data key:key];
}

@end



#pragma mark - ServiceResponse

NSString * const serviceResponseCodeKey = @"state";//@"code";
NSString * const serviceResponseDataKey = @"result";//@"data";
NSString * const serviceResponseMessageKey = @"msg";//@"message";

@interface ServiceResponse()

/**
 *  初始化服务端响应对象
 *
 *  @param code    响应代码
 *  @param message 消息
 *  @param data    数据
 *
 *  @return 响应对象
 */
- (instancetype)initWithCode:(ServiceResponseCode)code
                     message:(NSString *)message
                        data:(NSDictionary *)data;

@end

@implementation ServiceResponse

- (instancetype)initWithCode:(ServiceResponseCode)code
                     message:(NSString *)message
                        data:(NSDictionary *)data;
{
    if(self = [super init])
    {
        _code = code;
        _data = data;
        _message = message;
        _success = (code == ServiceResponseSuccess);
    }
    return self;
}

@end


#pragma mark - YCNetworManager

static BOOL isNetworkUse;
@interface YCNetworManager()

@property (nonatomic,strong) AFHTTPSessionManager *sessionManager;

@end

@implementation YCNetworManager

+ (instancetype)shareManager
{
    static YCNetworManager * _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instance = [[self alloc] init];
        _instance.baseURLString = YCAPIBaseUrl;
        _instance.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:_instance.baseURLString]];
        _instance.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        [_instance.sessionManager.requestSerializer setTimeoutInterval:30.0];//超时30秒
    });
    
    return _instance;
}


- (void)setAuthToken:(NSString *)authToken
{
    _authToken = authToken;
    [self.sessionManager.requestSerializer setValue:authToken forHTTPHeaderField:@"token"];
}

// 普通GET请求
- (NSURLSessionDataTask *)getWithUrl:(NSString *)Url params:(NSDictionary *)params success:(successBlock)successCallBack failure:(failureBlock)failureCallBack
{
    // 成功回调
    void (^ success)(NSURLSessionDataTask * task, id responseObject) = ^(NSURLSessionDataTask *task, id responseObject)
    {
        ServiceResponse *response = [[ServiceResponse alloc]
                                     initWithCode:[responseObject[serviceResponseCodeKey] unsignedIntegerValue]
                                     message:responseObject[serviceResponseMessageKey]
                                     data:responseObject[serviceResponseDataKey]];
        if(!response.success)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(response.code == ServiceResponseTokenInvalidate)//令牌失效
                {
                    //                    [self logout];
                }
                else
                {
                    NSString *message = response.message ? response.message : @"操作失败";
                    [SVProgressHUD showErrorWithStatus:message];
                }
            });
        }
        successCallBack(task,response);
    };
    // 失败回调
    void (^ failure)(NSURLSessionDataTask * task, NSError *error) = ^(NSURLSessionDataTask * task, NSError *error)
    {
        if(!(error.code == NSURLErrorCancelled && [error.domain isEqualToString:NSURLErrorDomain]))
        {
            if(error.code != NSURLErrorTimedOut)//请求超时
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
            }
        }
        failureCallBack(task,error);
    };
    
    NSString *urlString;
    if([Url hasPrefix:@"http://"])//智能拼接baseUrl
    {
        urlString = Url;
    }
    else
    {
        urlString = YCAPIBaseUrl;
        NSURL *baseURLString = [NSURL URLWithString:urlString];
        urlString = [[NSURL URLWithString:Url relativeToURL:baseURLString] absoluteString];
    }
    
    // 请求
    NSURLSessionDataTask *task = [self.sessionManager GET:urlString parameters:params progress:nil success:success failure:failure];

    return task;
}


// 普通POST请求
- (NSURLSessionDataTask *)postWithUrl:(NSString *)Url
                                    params:(NSDictionary *)params
                                   success:(successBlock)successCallBack
                                   failure:(failureBlock)failureCallBack
{
    
    NSURLSessionDataTask *task = [self postWithUrl:Url
                                               params:params
                                            fileDatas:nil
                                              success:successCallBack
                                              failure:failureCallBack];
    return task;
}


// 上传图片
- (NSURLSessionDataTask *)postWithUrl:(NSString *)Url
                                    params:(NSDictionary *)params
                                 fileDatas:(NSDictionary *)fileDatas
                                   success:(successBlock)successCallBack
                                   failure:(failureBlock)failureCallBack
{
    void (^ builFormData)(id <AFMultipartFormData> formData);
    if(fileDatas)
    {
        builFormData = ^(id<AFMultipartFormData> formData)
        {
            for(NSString *key in fileDatas.keyEnumerator)
            {
                NSArray *dataArray = fileDatas[key];
                for(NSData *data in dataArray)
                {
                    [formData appendPartWithFileData:data
                                                name:key
                                            fileName:[NSString stringWithFormat:@"%@.jpg",key]
                                            mimeType:@"image/jpeg"];
                }
            }
        };
    }
    else
    {
        builFormData = nil;
    }
    
    NSURLSessionDataTask *task = [self postWithUrl:Url
                                               params:params
                            constructingBodyWithBlock:builFormData
                                              success:successCallBack
                                              failure:failureCallBack];
    
    return task;
}


// 上传文件
- (NSURLSessionDataTask *)postWithUrl:(NSString *)Url
                                    params:(NSDictionary *)params
                 constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                                   success:(successBlock)successCallBack
                                   failure:(failureBlock)failureCallBack
{
    void (^ success)(NSURLSessionDataTask * task, id responseObject) = ^(NSURLSessionDataTask *task, id responseObject)
    {
        ServiceResponse *response = [[ServiceResponse alloc]
                                          initWithCode:[responseObject[serviceResponseCodeKey] unsignedIntegerValue]
                                          message:responseObject[serviceResponseMessageKey]
                                          data:responseObject[serviceResponseDataKey]];
        if(!response.success)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(response.code == ServiceResponseTokenInvalidate)//令牌失效
                {
//                    [self logout];
                }
                else
                {
                    NSString *message = response.message ? response.message : @"操作失败";
//                    [SVProgressHUD showErrorWithStatus:message];
                }
            });
        }
        successCallBack(task,response);
    };
    
    void (^ failure)(NSURLSessionDataTask * task, NSError *error) = ^(NSURLSessionDataTask * task, NSError *error)
    {
        if(!(error.code == NSURLErrorCancelled && [error.domain isEqualToString:NSURLErrorDomain]))
        {
            if(error.code != NSURLErrorTimedOut)//请求超时
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                });
            }
        }
        failureCallBack(task,error);
    };
    
    NSString *urlString;
    if([Url hasPrefix:@"http://"])//智能拼接baseUrl
    {
        urlString = Url;
    }
    else
    {
        urlString = YCAPIBaseUrl;
        NSURL *baseURLString = [NSURL URLWithString:urlString];
        urlString = [[NSURL URLWithString:Url relativeToURL:baseURLString] absoluteString];
    }
    
    NSURLSessionDataTask *task;
    
    if(block)//上传
    {
        task = [self.sessionManager POST:urlString parameters:params constructingBodyWithBlock:block progress:nil success:success failure:failure];
    }
    else
    {
        task = [self.sessionManager POST:urlString parameters:params progress:nil success:success failure:failure];
    }
    return task;
}

/**
 监控网络状态
 */
+ (BOOL)checkNetworkStatus {
    
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusUnknown) {
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusReachableViaWWAN){
            isNetworkUse = YES;
        } else if (status == AFNetworkReachabilityStatusNotReachable){
            // 网络异常操作
            isNetworkUse = NO;
            YCLog(@"网络异常,请检查网络是否可用！");
        }
    }];
    [reachabilityManager startMonitoring];
    return isNetworkUse;
}


@end
